package org.codegallery.jpagal.mybatis;

import java.io.Reader;

import javax.sql.DataSource;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import org.codegallery.jpagal.mybatis.mappers.Mapper1;

public class MyBatisUtil {
	public static SqlSessionFactory getSqlSessionFactory(){
		String resource = "mybatis/configuration.xml";
		SqlSessionFactory sqlSessionFactory=null;
		try{
			Reader reader = Resources.getResourceAsReader(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return sqlSessionFactory;
	}
	
	public static SqlSessionFactory getSqlSessionFactoryWithoutXml(){
		//todo get a data source
		DataSource dataSource = null;;
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		Environment environment =
		new Environment("development", transactionFactory, dataSource);
		Configuration configuration = new Configuration(environment);
		configuration.addMapper(Mapper1.class);
		SqlSessionFactory sqlSessionFactory =
		 new SqlSessionFactoryBuilder().build(configuration);
		return sqlSessionFactory;
	}
}
